import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Table, Button, Modal, message, Tag, Select, InputNumber, Input, Space, Popconfirm } from 'antd';
import { api } from '../utils/api';
import { EyeOutlined, ArrowUpOutlined, ArrowDownOutlined, DeleteOutlined } from '@ant-design/icons';

interface Question {
  id: number;
  title: string;
  type: string;
  difficulty: string;
  category: { name: string };
  sort_order?: number;
  score?: number;
  content?: string;
  options?: string[];
  explanation?: string;
}

const ExamQuestionManagement: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [questions, setQuestions] = useState<Question[]>([]);
  const [allQuestions, setAllQuestions] = useState<Question[]>([]);
  const [loading, setLoading] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [selectedQuestionIds, setSelectedQuestionIds] = useState<number[]>([]);
  const [addScore, setAddScore] = useState<number>(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [previewQuestion, setPreviewQuestion] = useState<Question | null>(null);
  const [search, setSearch] = useState('');
  const [filterType, setFilterType] = useState('');
  const [filterDifficulty, setFilterDifficulty] = useState('');
  const [filterCategory, setFilterCategory] = useState('');

  useEffect(() => {
    fetchExamQuestions();
  }, [id]);

  const fetchExamQuestions = async () => {
    setLoading(true);
    try {
      const res = await api.get(`/exams/admin/${id}/questions`);
      if (res.data.success) {
        setQuestions(res.data.data);
      }
    } finally {
      setLoading(false);
    }
  };

  const fetchAllQuestions = async () => {
    const res = await api.get('/questions/admin/', { params: { per_page: 1000 } });
    if (res.data.success) {
      setAllQuestions(res.data.data.items);
    }
  };

  const handleDelete = async (qid: number) => {
    await api.delete(`/exams/admin/${id}/questions/${qid}`);
    message.success('删除成功');
    fetchExamQuestions();
  };

  const handleBatchDelete = async () => {
    await Promise.all(selectedRowKeys.map(qid => api.delete(`/exams/admin/${id}/questions/${qid}`)));
    message.success('批量删除成功');
    setSelectedRowKeys([]);
    fetchExamQuestions();
  };

  const handleAdd = async () => {
    await api.post(`/exams/admin/${id}/questions`, { question_ids: selectedQuestionIds, score: addScore });
    message.success('添加成功');
    setAddModalVisible(false);
    setSelectedQuestionIds([]);
    fetchExamQuestions();
  };

  const handleOpenAddModal = async () => {
    await fetchAllQuestions();
    setAddModalVisible(true);
  };

  const handlePublish = async () => {
    // 校验题目数量和总分
    if (questions.length === 0) {
      message.error('请先添加题目再发布考试');
      return;
    }
    const totalScore = questions.reduce((sum, q) => sum + (q.score || 0), 0);
    if (totalScore < 1) {
      message.error('总分不能为0');
      return;
    }
    await api.post(`/exams/admin/${id}/publish`);
    message.success('考试已发布');
    fetchExamQuestions();
  };

  // 分值编辑
  const handleScoreChange = (qid: number, value: number | null) => {
    setQuestions(prev => prev.map(q => q.id === qid ? { ...q, score: value || 0 } : q));
  };
  const handleScoreBlur = async (qid: number, value: number | null) => {
    await api.post(`/exams/admin/${id}/questions/update`, {
      updates: [{ question_id: qid, score: value }]
    });
    message.success('分值已更新');
    fetchExamQuestions();
  };

  // 排序
  const moveQuestion = async (qid: number, direction: 'up' | 'down') => {
    const idx = questions.findIndex(q => q.id === qid);
    if (idx < 0) return;
    let newQuestions = [...questions];
    if (direction === 'up' && idx > 0) {
      [newQuestions[idx - 1], newQuestions[idx]] = [newQuestions[idx], newQuestions[idx - 1]];
    } else if (direction === 'down' && idx < questions.length - 1) {
      [newQuestions[idx], newQuestions[idx + 1]] = [newQuestions[idx + 1], newQuestions[idx]];
    }
    // 更新sort_order
    const updates = newQuestions.map((q, i) => ({ question_id: q.id, sort_order: i + 1, score: q.score }));
    await api.post(`/exams/admin/${id}/questions/update`, { updates });
    fetchExamQuestions();
  };

  // 题目详情预览
  const handlePreview = (q: Question) => setPreviewQuestion(q);

  // 筛选
  const filteredQuestions = allQuestions.filter(q => {
    return (
      (!search || q.title.includes(search)) &&
      (!filterType || q.type === filterType) &&
      (!filterDifficulty || q.difficulty === filterDifficulty) &&
      (!filterCategory || (q.category && q.category.name === filterCategory))
    );
  });

  const columns = [
    { title: '题目ID', dataIndex: 'id', key: 'id', width: 80 },
    { title: '标题', dataIndex: 'title', key: 'title', width: 300, render: (text: string, record: Question) => <Button type="link" onClick={() => handlePreview(record)}>{text}</Button> },
    { title: '类型', dataIndex: 'type', key: 'type', width: 100 },
    { title: '难度', dataIndex: 'difficulty', key: 'difficulty', width: 100 },
    { title: '分值', dataIndex: 'score', key: 'score', width: 100, render: (value: number, record: Question) => <InputNumber min={0} value={value} onChange={v => handleScoreChange(record.id, v)} onBlur={e => handleScoreBlur(record.id, record.score)} /> },
    { title: '顺序', dataIndex: 'sort_order', key: 'sort_order', width: 100, render: (_: any, record: Question, idx: number) => (
      <Space>
        <Button icon={<ArrowUpOutlined />} size="small" onClick={() => moveQuestion(record.id, 'up')} disabled={idx === 0} />
        <Button icon={<ArrowDownOutlined />} size="small" onClick={() => moveQuestion(record.id, 'down')} disabled={idx === questions.length - 1} />
      </Space>
    ) },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Question) => (
        <Popconfirm title="确定删除该题目吗？" onConfirm={() => handleDelete(record.id)}>
          <Button danger size="small" icon={<DeleteOutlined />}>删除</Button>
        </Popconfirm>
      )
    }
  ];

  return (
    <div>
      <h2>考试题目管理</h2>
      <Button type="primary" onClick={handleOpenAddModal} style={{ marginBottom: 16 }}>添加题目</Button>
      <Button onClick={() => navigate(-1)} style={{ marginLeft: 8 }}>返回</Button>
      <Button type="dashed" onClick={handlePublish} style={{ marginLeft: 8 }}>发布考试</Button>
      <Button danger onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0} style={{ marginLeft: 8 }}>批量删除</Button>
      <Table
        columns={columns}
        dataSource={questions}
        rowKey="id"
        loading={loading}
        pagination={false}
        style={{ marginTop: 16 }}
        size="small"
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys
        }}
      />
      <Modal
        title="添加题目"
        open={addModalVisible}
        onOk={handleAdd}
        onCancel={() => setAddModalVisible(false)}
      >
        <Space style={{ marginBottom: 8 }}>
          <Input placeholder="搜索题目" value={search} onChange={e => setSearch(e.target.value)} allowClear />
          <Select placeholder="类型" value={filterType} onChange={setFilterType} allowClear style={{ width: 100 }}>
            <Select.Option value="single_choice">单选</Select.Option>
            <Select.Option value="multiple_choice">多选</Select.Option>
            <Select.Option value="true_false">判断</Select.Option>
            <Select.Option value="fill_blank">填空</Select.Option>
          </Select>
          <Select placeholder="难度" value={filterDifficulty} onChange={setFilterDifficulty} allowClear style={{ width: 100 }}>
            <Select.Option value="easy">简单</Select.Option>
            <Select.Option value="medium">中等</Select.Option>
            <Select.Option value="hard">困难</Select.Option>
          </Select>
          <Select placeholder="分类" value={filterCategory} onChange={setFilterCategory} allowClear style={{ width: 120 }}>
            {[...new Set(allQuestions.map(q => q.category?.name).filter(Boolean))].map(name => (
              <Select.Option key={name} value={name}>{name}</Select.Option>
            ))}
          </Select>
          <InputNumber min={1} value={addScore} onChange={v => setAddScore(v || 10)} placeholder="分值" style={{ width: 80 }} />
        </Space>
        <Select
          mode="multiple"
          style={{ width: '100%' }}
          placeholder="请选择要添加的题目"
          value={selectedQuestionIds}
          onChange={setSelectedQuestionIds}
        >
          {filteredQuestions.filter(q => !questions.some(eq => eq.id === q.id)).map(q => (
            <Select.Option key={q.id} value={q.id}>{q.title}</Select.Option>
          ))}
        </Select>
      </Modal>
      <Modal
        title="题目详情"
        open={!!previewQuestion}
        onCancel={() => setPreviewQuestion(null)}
        footer={null}
      >
        {previewQuestion && (
          <div>
            <h3>{previewQuestion.title}</h3>
            <p>类型：{previewQuestion.type}</p>
            <p>难度：{previewQuestion.difficulty}</p>
            <p>分类：{previewQuestion.category?.name}</p>
            <p>分值：{previewQuestion.score}</p>
            <p>顺序：{previewQuestion.sort_order}</p>
            <div>
              <strong>内容：</strong>
              <div style={{ whiteSpace: 'pre-wrap' }}>{previewQuestion.content}</div>
            </div>
            {previewQuestion.options && previewQuestion.options.length > 0 && (
              <div>
                <strong>选项：</strong>
                <ul>
                  {previewQuestion.options.map((opt, idx) => <li key={idx}>{opt}</li>)}
                </ul>
              </div>
            )}
            {previewQuestion.explanation && (
              <div>
                <strong>解析：</strong>
                <div style={{ whiteSpace: 'pre-wrap' }}>{previewQuestion.explanation}</div>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ExamQuestionManagement;
